import Express from "express";
import { ITokenRequest } from "../tokenMiddleware";
import JournalService from "../../service/JournalService";
import ResponseHelper from "../utils/ResponseHelper";

const router = Express.Router();

router.get("/findByPage", async (req: ITokenRequest, res, next) => {
  const { UID } = req;
  try {
    const result = await JournalService.findByPage(UID);

    ResponseHelper.send(result, res, req);
  } catch (err) {
    next(err);
  }
});

router.get("/", async (req: ITokenRequest, res, next) => {
  const { UID } = req;
  const { mid } = req.query;

  try {
    const result = await JournalService.findByUidAndMid(UID, +mid);
    ResponseHelper.send(result, res, req);
  } catch (err) {
    next(err);
  }
});

router.get("/findById", async (req: ITokenRequest, res, next) => {
  const { UID } = req;

  try {
    const result = await JournalService.findById(UID, +req.query.id);
    ResponseHelper.send(result, res, req);
  } catch (err) {
    next(err);
  }
});

router.post("/", async (req: ITokenRequest, res, next) => {
  const { UID } = req;

  try {
    req.body.u_id = UID;
    const result = await JournalService.add(req.body);
    ResponseHelper.send(result, res, req);
  } catch (err) {
    next(err);
  }
});

router.put("/", async (req: ITokenRequest, res, next) => {
  const { UID } = req;

  try {
    req.body.u_id = UID;
    const result = await JournalService.modify(req.body);
    ResponseHelper.send(result, res, req);
  } catch (err) {
    next(err);
  }
});

router.get("/findOpenJournal", async (req: ITokenRequest, res, next) => {
  const { mid, uid } = req.query;

  try {
    const result = await JournalService.findOpenJournalList({
      u_id: +uid,
      m_id: +mid,
    });
    ResponseHelper.send(result, res, req);
  } catch (err) {
    next(err);
  }
});

router.get("/findOneOpenJournal", async (req: ITokenRequest, res, next) => {
  const { mid, uid, id } = req.query;

  try {
    const result = await JournalService.findOneOpenJournal({
      u_id: +uid,
      m_id: +mid,
      id: +id,
    });
    ResponseHelper.send(result, res, req);
  } catch (err) {
    next(err);
  }
});

router.delete("/:id", async (req: ITokenRequest, res, next) => {
  const { UID } = req;

  try {
    const result = await JournalService.del(UID, +req.params.id);
    return ResponseHelper.send(result, res, req);
  } catch (err) {
    next(err);
  }
});

export default router;
